package caro.app.service;

import caro.app.business.PlayerManagement;
import caro.app.business.Session;
import caro.app.business.ThreadManagement;
import caro.app.business.UserManagementImpl;
import java.io.IOException;
import java.net.*;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 * Class ServerSocketProvider
 * @author Thanh Nhan
 * @Since Aug 14, 2011
 * @Version 1.0
 */
public class ServerSocketProvider {
    private static final int port = 2212;
    private static final Logger logger = Logger.getLogger("ServerLog");
    public static void main(String a[]){
        PlayerManagement players = new PlayerManagement();
        List<Session> sessions = new LinkedList<Session>();
        ThreadManagement threads = new ThreadManagement();
        try {
            //Khoi tao server
            logger.log(Level.INFO, "Khoi tao server socket...");
            ServerSocket server = new ServerSocket(port);
            logger.log(Level.INFO, "Server socket [Ip: {0}] duoc khoi tao thanh cong!", new Object[]{server.getLocalSocketAddress()});
            //Lang nghe ket noi tu client
            while(true){
                logger.log(Level.INFO, "Dang lang nghe yeu cau tu client...");
                Socket client = server.accept();
                logger.log(Level.INFO, "Client {0}, cong {1} dang ket noi...", new Object[]{client.getInetAddress(), client.getPort()});
                //Trai qua giai doan chung thuc
                LoginService userManagement = new UserManagementImpl(client, players, sessions);
                logger.log(Level.INFO,"Dang tao luong cho client...");
                Thread thread = new Thread(userManagement);
                threads.addThread(thread);
                thread.start();
                logger.log(Level.INFO,"Khoi tao thanh cong!");
            }
        } catch (IOException ex) {
            logger.log(Level.SEVERE, ex.getMessage());
        }
    }
    
}
